<template>
  <div class="class-container">
    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <span class="error-icon">⚠️</span>
      {{ error }}
      <el-button type="primary" size="small" @click="fetchClassData" class="retry-button">
        重试
      </el-button>
    </div>

    <!-- 数据不一致提示 -->
    <div v-if="dataInconsistency" class="warning-message">
      <span class="warning-icon">ℹ️</span>
      {{ dataInconsistency }}
      <el-button type="warning" size="small" @click="fetchClassData" class="retry-button">
        重新加载
      </el-button>
    </div>

    <!-- 原有的班级内容 -->
    <div v-if="!$route.path.includes('analysis') && !$route.path.includes('warning')">
      <!-- 顶部信息 -->
      <div class="class-header">
        <div class="class-info">
          <h1>{{ classInfo.name }}</h1>
          <p>{{ classInfo.college }} | {{ classInfo.grade }}</p>
          <p v-if="classInfo.teacherName">班主任: {{ classInfo.teacherName }}</p>
        </div>
        <div class="back-btn" @click="$router.go(-1)">
          <span class="icon">←</span> 返回
        </div>
      </div>
      
      <!-- 加载指示器 -->
      <el-skeleton :loading="loading" animated>
        <template #template>
          <div class="loading-skeleton">
            <el-skeleton-item variant="p" style="width: 100%; height: 60px" />
            <div style="display: flex; justify-content: space-between; margin-top: 20px">
              <el-skeleton-item variant="p" style="width: 24%; height: 100px" />
              <el-skeleton-item variant="p" style="width: 24%; height: 100px" />
              <el-skeleton-item variant="p" style="width: 24%; height: 100px" />
              <el-skeleton-item variant="p" style="width: 24%; height: 100px" />
            </div>
          </div>
        </template>

        <template #default>
          <!-- 班级统计卡片 -->
          <div class="stats-cards">
            <div class="stat-card">
              <div class="stat-icon student-icon">👥</div>
              <div class="stat-info">
                <div class="stat-value">{{ classInfo.studentCount }}</div>
                <div class="stat-label">总人数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon course-icon">📚</div>
              <div class="stat-info">
                <div class="stat-value">{{ classInfo.courseCount || '暂无' }}</div>
                <div class="stat-label">课程数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon score-icon">📊</div>
              <div class="stat-info">
                <div class="stat-value">{{ classInfo.avgScore || '暂无' }}</div>
                <div class="stat-label">平均分</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon rank-icon">⭐</div>
              <div class="stat-info">
                <div class="stat-value">{{ classInfo.ranking || '暂无' }}</div>
                <div class="stat-label">年级排名</div>
              </div>
            </div>
          </div>
        </template>
      </el-skeleton>

      <!-- 分析功能入口 -->
      <div class="analysis-cards">
        <router-link 
          :to="`/admin/class/${collegeId}/${gradeId}/${classId}/learning-analysis`" 
          class="analysis-card">
          <div class="card-icon">📊</div>
          <div class="card-content">
            <h3>学情分析</h3>
            <p>分析学生学习数据，预测学习潜能和问题焦点</p>
          </div>
        </router-link>

        <router-link 
          :to="`/admin/class/${collegeId}/${gradeId}/${classId}/warning-system`" 
          class="analysis-card">
          <div class="card-icon">⚠️</div>
          <div class="card-content">
            <h3>预警系统</h3>
            <p>智能预警系统，及时发现学习问题</p>
          </div>
        </router-link>
      </div>

      <!-- 学生列表 -->
      <div class="student-section">
        <div class="section-header">
          <h2>学生名单</h2>
          <div class="header-actions">
            <div class="search-box">
              <el-input
                v-model="searchText"
                placeholder="搜索学生..."
                prefix-icon="el-icon-search"
                clearable
              />
            </div>
            <el-button type="primary" icon="el-icon-plus" @click="showAddStudentDialog = true">
              添加学生
            </el-button>
          </div>
        </div>

        <el-table
          v-loading="studentsLoading"
          :data="filteredStudents"
          border
          style="width: 100%"
          @row-click="goToStudentDetail"
          empty-text="暂无学生数据"
        >
          <el-table-column prop="id" label="学号" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="gender" label="性别" width="80" />
          <el-table-column prop="rank" label="班级排名" width="100">
            <template #default="scope">
              <el-tag size="small" type="success" v-if="scope.row.rank <= 5">#{{ scope.row.rank }}</el-tag>
              <el-tag size="small" type="warning" v-else-if="scope.row.rank <= 15">#{{ scope.row.rank }}</el-tag>
              <el-tag size="small" type="info" v-else>#{{ scope.row.rank }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="attendance" label="出勤率">
            <template #default="scope">
              <el-progress 
                :percentage="scope.row.attendance" 
                :color="getAttendanceColor(scope.row.attendance)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" type="primary" @click.stop="viewStudentDetails(scope.row.id)">
                详情
              </el-button>
              <el-button size="small" type="danger" @click.stop="confirmDeleteStudent(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 添加学生对话框 -->
    <el-dialog
      title="添加学生"
      v-model="showAddStudentDialog"
      width="500px"
    >
      <el-form :model="newStudent" label-width="100px">
        <el-form-item label="学号">
          <el-input v-model="newStudent.id" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="newStudent.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="newStudent.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddStudentDialog = false">取消</el-button>
        <el-button type="primary" @click="addStudent" :loading="addingStudent">添加</el-button>
      </template>
    </el-dialog>
    
    <!-- 子路由视图 -->
    <router-view v-if="$route.path.includes('analysis') || $route.path.includes('warning')"></router-view>
  </div>
</template>

<script setup>
/**
 * @file Class.vue
 * @description 班级详情组件，显示班级信息及学生列表
 * @created 2024-06-25
 */
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { classAPI } from '@/api/admin/college'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const searchText = ref('')
const dataInconsistency = ref(null)

// 班级基本信息
const classInfo = ref({
  name: '加载中...',
  college: '加载中...',
  grade: '加载中...',
  studentCount: 0,
  courseCount: 0,
  avgScore: 0,
  ranking: 0,
  teacherName: ''
})

// 学生列表相关状态
const students = ref([])
const loading = ref(false)
const studentsLoading = ref(false)
const error = ref(null)
const showAddStudentDialog = ref(false)
const addingStudent = ref(false)
const newStudent = ref({
  id: '',
  name: '',
  gender: '男'
})

// 计算过滤后的学生列表
const filteredStudents = computed(() => {
  if (!searchText.value) return students.value
  
  const keyword = searchText.value.toLowerCase()
  return students.value.filter(student => 
    student.name.toLowerCase().includes(keyword) || 
    String(student.id).toLowerCase().includes(keyword)
  )
})

// 获取路由参数
const { collegeId, gradeId, classId } = route.params

/**
 * 获取班级详情数据
 * @description 请求班级基本信息和学生列表，确保数据一致性
 */
const fetchClassData = async () => {
  loading.value = true
  studentsLoading.value = true
  error.value = null
  
  try {
    console.log(`正在请求班级数据: collegeId=${collegeId}, gradeId=${gradeId}, classId=${classId}`)
    
    // 获取班级基本信息
    const classRes = await classAPI.getClass(collegeId, gradeId, classId)
    console.log('班级基本信息响应:', classRes)
    
    if (classRes) {
      classInfo.value = {
        name: classRes.name || '未命名班级',
        college: classRes.college || '未知学院',
        grade: classRes.grade || '未知年级',
        studentCount: classRes.studentCount || 0,
        courseCount: classRes.courseCount || 0,
        avgScore: classRes.avgScore || 0,
        ranking: classRes.ranking || '-',
        teacherName: classRes.teacherName || '暂无班主任'
      }
      
      // 获取班级学生列表
      await fetchStudents()
      
      // 数据一致性检查
      validateDataConsistency()
    }
  } catch (err) {
    console.error('获取班级数据失败:', err)
    error.value = '获取班级数据失败，请稍后重试'
    
    // 检查错误状态码，提供更具体的错误信息
    if (err.response) {
      if (err.response.status === 404) {
        error.value = '班级功能目前不可用或该班级不存在'
      } else if (err.response.status === 403) {
        error.value = '您没有权限访问该班级数据'
      } else if (err.response.status >= 500) {
        error.value = '服务器错误，请联系管理员'
      }
    }
    
    // 使用模拟数据（仅在开发环境）
    if (import.meta.env.DEV) {
      useBackupData()
      // 确保模拟数据也进行一致性校验
      validateDataConsistency()
    }
  } finally {
    loading.value = false
  }
}

/**
 * 获取班级学生列表
 */
const fetchStudents = async () => {
  studentsLoading.value = true
  
  try {
    const studentsRes = await classAPI.getClassStudents(collegeId, gradeId, classId)
    console.log('班级学生列表响应:', studentsRes)
    
    if (studentsRes && Array.isArray(studentsRes)) {
      students.value = studentsRes.map(student => ({
        id: student.id || student.studentId,
        name: student.name,
        gender: student.gender || '未知',
        rank: student.rank || Math.floor(Math.random() * 30) + 1,
        attendance: student.attendance || Math.floor(Math.random() * 20) + 80
      }))
      
      // 更新班级学生数量，确保与列表一致
      if (classInfo.value) {
        classInfo.value.studentCount = students.value.length
      }
    } else {
      students.value = []
      
      // 如果API返回空数据但班级信息显示有学生，记录警告
      if (classInfo.value && classInfo.value.studentCount > 0) {
        console.warn('数据不一致: 班级学生数量为 ' + classInfo.value.studentCount + '，但学生列表为空')
      }
    }
  } catch (err) {
    console.error('获取学生列表失败:', err)
    ElMessage.error('获取学生列表失败，请刷新重试')
    students.value = []
    
    // 在开发环境下使用模拟数据
    if (import.meta.env.DEV) {
      // 只有在班级信息显示有学生时才生成模拟数据
      if (classInfo.value && classInfo.value.studentCount > 0) {
        students.value = generateMockStudents(classInfo.value.studentCount)
      }
    }
  } finally {
    studentsLoading.value = false
  }
}

/**
 * 验证数据一致性
 * @description 确保班级信息和学生列表数据一致
 */
const validateDataConsistency = () => {
  if (!classInfo.value) return
  
  // 清除之前的不一致提示
  dataInconsistency.value = null
  
  // 如果班级显示有学生但学生列表为空
  if (classInfo.value.studentCount > 0 && students.value.length === 0) {
    console.warn('数据不一致：班级显示有 ' + classInfo.value.studentCount + ' 名学生，但学生列表为空')
    
    // 在开发环境下，生成模拟学生数据以保持一致性
    if (import.meta.env.DEV) {
      students.value = generateMockStudents(classInfo.value.studentCount)
    } else {
      // 在生产环境，调整班级学生数量以匹配实际学生列表
      dataInconsistency.value = `班级信息显示有 ${classInfo.value.studentCount} 名学生，但无法获取学生列表数据`
      classInfo.value.studentCount = 0
    }
  } else if (classInfo.value.studentCount === 0 && students.value.length > 0) {
    // 如果学生列表有数据但班级显示没有学生
    console.warn('数据不一致：班级显示没有学生，但学生列表有 ' + students.value.length + ' 名学生')
    dataInconsistency.value = `班级信息显示无学生，但实际有 ${students.value.length} 名学生数据`
    classInfo.value.studentCount = students.value.length
  }
}

/**
 * 生成后备数据（仅用于开发环境）
 */
const useBackupData = () => {
  // 生成班级模拟数据
  classInfo.value = {
    name: `计算机科学${classId}班`,
    college: '计算机科学与技术学院',
    grade: `${gradeId}级`,
    studentCount: 30,
    courseCount: 8,
    avgScore: 85.6,
    ranking: 2,
    teacherName: '张老师'
  }
  
  // 生成学生模拟数据
  students.value = generateMockStudents(classInfo.value.studentCount)
}

/**
 * 生成模拟学生数据
 * @param {number} count - 要生成的学生数量
 * @returns {Array} 模拟学生数据列表
 */
const generateMockStudents = (count = 30) => {
  return Array(count).fill(null).map((_, index) => ({
    id: `2023${String(index + 1).padStart(2, '0')}`,
    name: `学生${index + 1}`,
    gender: Math.random() > 0.5 ? '男' : '女',
    rank: Math.floor(Math.random() * 30) + 1,
    attendance: Math.floor(Math.random() * 20) + 80
  }))
}

/**
 * 获取出勤率颜色
 * @param {number} attendance - 出勤率
 * @returns {string} 对应的颜色
 */
const getAttendanceColor = (attendance) => {
  if (attendance >= 90) return '#67C23A'
  if (attendance >= 80) return '#E6A23C'
  return '#F56C6C'
}

/**
 * 查看学生详情
 * @param {number} studentId - 学生ID
 */
const viewStudentDetails = (studentId) => {
  router.push(`/admin/student/${collegeId}/${gradeId}/${classId}/${studentId}`)
}

/**
 * 点击表格行，跳转到学生详情
 * @param {Object} row - 表格行数据
 */
const goToStudentDetail = (row) => {
  viewStudentDetails(row.id)
}

/**
 * 确认删除学生
 * @param {Object} student - 学生信息
 */
const confirmDeleteStudent = (student) => {
  ElMessageBox.confirm(
    `确定要删除学生 ${student.name} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际项目中应调用删除API
    students.value = students.value.filter(item => item.id !== student.id)
    
    // 更新班级学生总数
    classInfo.value.studentCount = students.value.length
    
    // 验证数据一致性
    validateDataConsistency()
    
    ElMessage.success(`删除学生 ${student.name} 成功`)
  }).catch(() => {
    // 取消操作
  })
}

/**
 * 添加学生
 */
const addStudent = () => {
  // 表单验证
  if (!newStudent.value.id || !newStudent.value.name) {
    ElMessage.warning('请填写完整的学生信息')
    return
  }
  
  addingStudent.value = true
  
  // 模拟API请求
  setTimeout(() => {
    // 实际项目中应该调用添加学生API
    students.value.unshift({
      ...newStudent.value,
      rank: 0,
      attendance: 100
    })
    
    // 更新班级学生总数
    classInfo.value.studentCount = students.value.length
    
    // 验证数据一致性
    validateDataConsistency()
    
    ElMessage.success('添加学生成功')
    showAddStudentDialog.value = false
    
    // 重置表单
    newStudent.value = {
      id: '',
      name: '',
      gender: '男'
    }
    
    addingStudent.value = false
  }, 1000)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchClassData()
})
</script>

<style scoped>
.class-container {
  padding: 30px;
  background: #f0f2f5;
  min-height: 100vh;
}

.class-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.class-info h1 {
  font-size: 24px;
  margin-bottom: 8px;
  color: #333;
}

.class-info p {
  color: #666;
  margin-bottom: 4px;
}

.back-btn {
  padding: 8px 16px;
  background: #f0f2f5;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  font-size: 24px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.student-icon {
  background-color: #e6f7ff;
  color: #1890ff;
}

.course-icon {
  background-color: #f6ffed;
  color: #52c41a;
}

.score-icon {
  background-color: #fff7e6;
  color: #fa8c16;
}

.rank-icon {
  background-color: #fff0f6;
  color: #eb2f96;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.analysis-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.analysis-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-decoration: none;
  color: inherit;
}

.analysis-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-icon {
  font-size: 24px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f5f5f5;
}

.card-content h3 {
  margin-bottom: 8px;
  color: #333;
}

.card-content p {
  color: #666;
  font-size: 14px;
}

.student-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.search-box {
  width: 250px;
}

/* 错误消息样式 */
.error-message {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #f5222d;
}

.error-icon {
  font-size: 20px;
}

.retry-button {
  margin-left: auto;
}

/* 加载骨架屏样式 */
.loading-skeleton {
  margin-bottom: 24px;
}

/* 数据不一致提示样式 */
.warning-message {
  background: #fff7e6;
  border: 1px solid #ffd666;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #d48806;
}

.warning-icon {
  font-size: 20px;
}
</style> 